/****************************************************
          File Name:46-6-client.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sat 13 Sep 2014 09:05:07 AM CST
*****************************************************/

#include"msg.h"
#include<fcntl.h>
#include<string.h>

int main(int argc,char *argv[])
{
    struct msgbuf msg;
    int client,server;
    int perm=S_IRUSR|S_IWUSR|S_IWGRP;
    char *buf;                          // store which one to talk to
    char *message;
    int i=0;

    if((buf=malloc(DATA_SIZE))==NULL)
        err("malloc");
    if((message=malloc(DATA_SIZE))==NULL)
        err("malloc message");

    if((server=msgget(key,S_IRUSR))==-1)
        err("get server id");
    if((client=msgget(IPC_PRIVATE,IPC_CREAT|perm))==-1)
        err("creat private id");
	
	msg.mtype=1;	// test
	
    for(;;)
    {
		printf("input target client ID:\t");
        if(fgets(buf,DATA_SIZE,stdin)==NULL)  // get target user
            err("get input");
        if(buf[0]=='\n')
		{
			msgctl(client,IPC_RMID,NULL);
            exit(0);
		}
		
        msg.id=atol(buf);   // tranform target id into number
		printf("I am: %d\n",client);
	
        for(;;)
        {
            if(fgets(message,DATA_SIZE,stdin)==NULL)
				break;
			msg.id=atol(buf);   // tranform target id into number
			strcpy(msg.mtext,message);
			
			if(message[0]!='\n')
				if(msgsnd(server,&msg,DATA_SIZE,0)==-1) // msg contents target id
					err("send to user");
            if(msgrcv(client,&msg,DATA_SIZE,1,IPC_NOWAIT)==-1)       // wait && block
			{
				if(errno==ENOMSG)
					continue;
				else
					err("recive message from server");
			}
			
            printf("%s\n",msg.mtext);

        }

    }

}
